package dynamicCompile;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;

/**
 * @ClassName Demo01
 * @Description TODO
 * 传入字符串，写入临时文件，编译执行
 * @Author liang
 * @Date 2018/10/18 14:17
 * @Version 1.0
 **/
public class Demo01 {
    public static void main(String [] args) throws IOException {
        //将字符串存储成一个临时文件，然后掉用动态方法
        String str = "public class Hi { public static void main(String args[]){System.out.println(\"say hi .. \");}    }";
        File file = new File("Hi.java");
        if(!file.exists()){
            file.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fileWriter);
        out.write(str,0,str.length());
        out.close();
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        //int run = compiler.run(null, null, null, "D:/a_code/HelloWord.java");
        int run = compiler.run(null, null, null, "Hi.java");
        System.out.println(run);
        Runtime runtime = Runtime.getRuntime();
        Process exec = runtime.exec("java -cp D:/a_code/dataSendClient    Hi");
        InputStream in = exec.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String info = "";
        while((info = reader.readLine())!=null){
            System.out.println(info);
        }
        /** 通过反射运行  **/

    }
}
